package com.infomanage.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.infomanage.exception.DaoException;
import com.infomanage.po.Department;
import com.infomanage.po.HibernateSessionFactory;

public class DeptDAO extends BaseDAO<Department>{
	
	public List<Department> findChildren(int parentId) throws DaoException{
		Session session = HibernateSessionFactory.getSession();
		List<Department> list = null;
		try {
			Query query =  session.createQuery("from Department where parent = ?");
			query.setInteger(0, parentId);
			list = query.list();
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return list;
	}
	
	public Department findById(int id) throws DaoException{
		return super.find(Department.class, id);
	}
	
	public List<Department> findByLevel(int level) throws DaoException{
		Session session = HibernateSessionFactory.getSession();
		List<Department> list = null;
		try {
			Query query =  session.createQuery("from Department where level = ?");
			query.setInteger(0, level);
			list = query.list();
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return list;
	}
	
	public boolean isChildOf(int srcDept, int desDept) throws DaoException{
		if(srcDept == desDept) return true;
		List<Department> children  = findChildren(desDept);
		if(children != null){
			for(Department dept : children){
				if(dept.getDeptId() == srcDept){
					return true;
				}
			}
		}
		return false;
	}
	
	public String findDeptPath(int id) {
		StringBuffer buff = new StringBuffer();
		try {
			while (true) {
				Department dept = find(Department.class, id);
				if (dept == null)
					break;
				buff.insert(0, dept.getName());
				int level = dept.getLevel();
				if(level == 2){
					break;
				}
				id = dept.getParent();
			}
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buff.toString();
	}
	public int getMaxDeptID(){
		Session session = HibernateSessionFactory.getSession();
		List<Department> list = null;
		try {
			Query query =  session.createQuery("from Department order by deptId desc");
			
			list = query.list();
		} catch (Exception e) {
		     e.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
		Department department=(Department)list.get(0);
		int dept_id=department.getDeptId();
		return dept_id;
	}
}
